<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model;

use app\api\model\UserOauth as UserOauthModel;
use app\api\service\User as UserService;
use app\common\model\store\Setting as SettingModel;
use app\common\model\User as UserModel;
use cores\exception\BaseException;
use think\facade\Cache;
use yiovo\captcha\facade\CaptchaApi;

/**
 * 用户模型类
 * Class User
 * @package app\api\model
 */
class User extends UserModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'open_id',
		'is_delete',
		'store_id',
		'create_time',
		'update_time',
	];

	/**
	 * 获取器：隐藏手机号中间四位
	 * @param string $value
	 * @return string
	 */
	// public function getMobileAttr(string $value): string {
	// 	return strlen($value) === 11 ? hide_mobile($value) : $value;
	// }

	/**
	 * 获取用户信息
	 * @param string $token
	 * @return User|array|false|null
	 * @throws BaseException
	 */
	public static function getUserByToken(string $token) {
		// 检查登录态是否存在
		if (!Cache::has($token)) {
			return false;
		}
		// 用户的ID
		$userId = (int) Cache::get($token)['user']['user_id'];
		// 用户基本信息
		$userInfo = self::detail($userId);
		if (empty($userInfo) || $userInfo['is_delete']) {
			throwError('很抱歉，用户信息不存在或已删除', config('status.not_logged'));
		}
		// 获取用户关联的第三方用户信息(当前客户端)
		try {
			$userInfo['currentOauth'] = UserOauthModel::getOauth($userId, getPlatform());
		} catch (\Throwable $e) {
			throwError($e->getMessage());
		}
		return $userInfo;
	}

	/**
	 * 绑定手机号(当前登录用户)
	 * @param array $data
	 * @return bool
	 * @throws BaseException
	 */
	public function bindMobile(array $data): bool {
		// 当前登录的用户信息
		$userInfo = UserService::getCurrentLoginUser(true);
		// 验证绑定的手机号
		$this->checkBindMobile($data);
		// 更新手机号记录
		return $userInfo->save(['mobile' => $data['mobile']]);
	}

	public function increased(array $form, $role): bool {
		$password = SettingModel::getItem('trade', 10001)['order']['password'];
		foreach ($form as $key => $item) {
			$userInfo = self::detail(['mobile' => $item['phone']]);
			$data['nick_name'] = $item['name'];
			$data['grade_id'] = $role;
			if ($userInfo) {

				$userInfo->save($data);
				continue;
			}
			// 默认数据
			$data['mobile'] = $item['phone'];
			$data['store_id'] = self::$storeId;

			$data['password'] = $password;
			$data['nick_name'] = $item['name'];
			$this->save($data);
		}

		// 更新用户记录
		return true;
	}

	/**
	 * 修改个人信息（头像昵称）
	 * @param array $form
	 * @return bool
	 * @throws BaseException
	 */
	public function personal(array $form): bool {
		// 当前登录的用户信息
		$userInfo = UserService::getCurrentLoginUser(true);
		// 默认数据
		$data['avatar_id'] = $form['avatarId'] ?: $userInfo['avatar_id'];
		$data['nick_name'] = $form['nickName'] ?: $userInfo['nick_name'];
		// 更新用户记录
		return $userInfo->save($data);
	}
	public function idcard(array $form): bool {
		// 当前登录的用户信息
		$userInfo = UserService::getCurrentLoginUser(true);
		// 默认数据

		$data['idcard_id1'] = $form['idcardId1'] ?: $userInfo['idcard_id1'];
		$data['idcard_id2'] = $form['idcardId2'] ?: $userInfo['idcard_id2'];

		// 更新用户记录
		return $userInfo->save($data);
	}
	/**
	 * 验证绑定的手机号
	 * @param array $data
	 * @return void
	 * @throws BaseException
	 */
	private function checkBindMobile(array $data): void {
		// 验证短信验证码是否匹配
		if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
			throwError('短信验证码不正确');
		}
		// 判断手机号是否已存在
		if (static::checkExistByMobile($data['mobile'])) {
			throwError('很抱歉，该手机号已绑定其他账户');
		}
	}
}
